package cm.mefobe.android.telecomcost.dialog;

import java.util.ArrayList;

import com.google.gson.Gson;

import cm.mefobe.android.telecomcost.R;
import cm.mefobe.android.telecomcost.DatabaseManager;
import cm.mefobe.android.telecomcost.TelecomCost;
import cm.mefobe.android.telecomcost.activities.ProviderListActivity;
import cm.mefobe.android.telecomcost.entities.Country;
import cm.mefobe.android.telecomcost.entities.Provider;
import cm.mefobe.android.telecomcost.entities.Zone;
import cm.mefobe.android.telecomcost.view.CountrySpinner;
import cm.mefobe.android.telecomcost.view.ZoneSpinner;
import android.app.Dialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import android.widget.ViewFlipper;

public class ProviderDialog extends Dialog {

	private DatabaseManager db;
	private EditText txtName;
	private Zone _zone = null;
	private ArrayList<Zone> zones;
	private ArrayList<Country> countries;
	private Provider _provider;
	private Context _context;
	private Country _country;
	private ZoneSpinner zones_list;
	private CountrySpinner country_list;
	private EditText txtPref1;
	private EditText txtPref2;
	private EditText txtPref3;
	private EditText txtPref4;
	private ViewFlipper flipper;
	long id = -1;
	private int viewIndex = 0;
	private boolean shouldRefreshProviderList = false;
	private Button btnNext;
	private Button btnPrevious;
	private Button btnClose;

	/**
	 * @param context
	 * @param cancelable
	 * @param cancelListener
	 */
	public ProviderDialog(Context context, boolean cancelable,
			OnCancelListener cancelListener) {
		super(context, cancelable, cancelListener);
		_context = context;
	}

	/**
	 * @param context
	 * @param theme
	 */
	public ProviderDialog(Context context, int theme) {
		super(context, theme);
		_context = context;
	}

	public ProviderDialog(Context context, Provider Provider) {
		super(context);
		_provider = Provider;
		_context = context;
	}

	private boolean setProvider() {
		_country = country_list.getSelectedCountry();
		if (_country == null || _country.getName() == null) {
			Toast.makeText(_context,
					"Please select a country for the Provider", 3).show();
			return false;
		} else {
			String name = txtName.getText().toString();

			if (name.equals("")) {
				Toast.makeText(getOwnerActivity(),
						"Please enter the name of the Provider and the code", 3)
						.show();
				return false;
			} else {
				id = _provider == null ? -1 : _provider.getId();
				_provider = _provider == null ? new Provider() : _provider;

				Provider provider = ((ProviderListActivity) _context)
						.getProvider(name);
				if (provider != null && (provider.getId() != _provider.getId())) {
					Toast.makeText(_context,
							"A provider already exists with the same name", 3)
							.show();
					return false;
				}

				_provider.setId(id == -1 ? db.getNextId() : id);
				_provider.setName(name);
				_provider.setCountryId(_country.getId());
				return true;
			}
		}
	}

	private boolean saveProvider() {
		Log.i("ProviderListActivity",
				"saving the provider id = " + _provider.getId());

		String _prefixes = "";
		_prefixes = txtPref1.getText().toString().length() > 0 ? _prefixes
				+ txtPref1.getText().toString() + ";" : _prefixes;
		_prefixes = txtPref2.getText().toString().length() > 0 ? _prefixes
				+ txtPref2.getText().toString() + ";" : _prefixes;
		_prefixes = txtPref3.getText().toString().length() > 0 ? _prefixes
				+ txtPref3.getText().toString() + ";" : _prefixes;
		_prefixes = txtPref4.getText().toString().length() > 0 ? _prefixes
				+ txtPref4.getText().toString() + ";" : _prefixes;

		if (_prefixes.equals("")) {
			Toast.makeText(_context,
					"You must specify at last one prefix for this provider", 4)
					.show();
			return false;
		}

		_provider.setPrefixes(_prefixes);
		shouldRefreshProviderList = true;
		Toast.makeText(
				_context,
				db.saveProvider(_provider, _country, id) ? "provider saved !!!"
						: "could not save this provider", 3).show();
		id = _provider.getId();
		return true;
	}

	public void setProvider(Provider Provider) {
		_provider = Provider;
	}

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.i("EditProviderDialog", "Creating the dialog...");
		super.onCreate(savedInstanceState);

		db = TelecomCost.getDatabaseManager();
		setContentView(R.layout.edit_provider);

		setTitle("Edit a Provider");

		btnNext = (Button) findViewById(R.id.btnNext);
		btnPrevious = (Button) findViewById(R.id.btnPrevious);
		btnClose = (Button) findViewById(R.id.btnClose);

		flipper = (ViewFlipper) findViewById(R.id.viewFlipper1);
		country_list = (CountrySpinner) findViewById(R.id.spinnerCountries);
		zones_list = (ZoneSpinner) findViewById(R.id.spinnerZones);
		txtName = (EditText) findViewById(R.id.txtProviderName);
		txtPref1 = (EditText) findViewById(R.id.txtPref1);
		txtPref2 = (EditText) findViewById(R.id.txtPref2);
		txtPref3 = (EditText) findViewById(R.id.txtPref3);
		txtPref4 = (EditText) findViewById(R.id.txtPref4);

		country_list.setZoneSpinner(zones_list);

		btnClose.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				hide();
			}
		});

		btnNext.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showNextView();
			}
		});

		btnPrevious.setOnClickListener(new View.OnClickListener() {

			public void onClick(View v) {
				showPreviousView();
			}
		});

		Log.i("EditProviderDialog", "Dialog ohne bundle created....");
	}

	protected void showPreviousView() {
		btnNext.setText("Next");
		flipper.showPrevious();
		viewIndex--;
	}

	protected void showNextView() {
		switch (viewIndex) {
		case 0:
			if (preparePrefixDialog()) {
				flipper.showNext();
				viewIndex++;
			}
			break;
		case 1:
			if (saveProvider()) {
				closeDialog();
			}
			break;
		default:
			throw new IndexOutOfBoundsException();
		}
	}

	protected void closeDialog() {
		Log.i("ProviderListActivity",
				"closing the dialog, binding the providers");
		if (viewIndex == 1) {
			flipper.showPrevious();
			viewIndex = 0;
		}

		hide();
		resetDialog();
		if (shouldRefreshProviderList) {
			((ProviderListActivity) _context).bindProvider();
		}
	}

	private void bindProvider() {
		Log.i("EditProviderDialog", "binding the provider...");
		txtName.setText(_provider != null ? _provider.getName() : "");
		if (_provider != null) {
			Gson gson = TelecomCost.getGson();
			Log.i("EditProviderDialog", "loading the country for the provider "
					+ _provider.getName());
			_country = gson.fromJson(
					db.getData(Country.PROP_TYPE, _provider.getCountryId()),
					Country.class);
			if (_country != null) {
				Log.i("EditProviderDialog", "country " + _country.getName()
						+ " loaded...we set the zone for this country");
				int index = 0;
				while (index < zones.size()) {
					if (_country.getZoneId() == zones.get(index).getId()) {
						zones_list.setSelection(index, true);
						Log.i("EditProviderDialog", "zone "
								+ zones.get(index).getName() + " set...");
						index = zones.size();
					}

					index++;
				}
			} else {
				Log.i("EditProviderDialog",
						"could not load the country for the provider "
								+ _provider.getName());
			}
		}
	}

	protected boolean preparePrefixDialog() {
		if (setProvider()) {
			if (!_provider.getPrefixes().equals("")) {
				String[] prefixes = _provider.getPrefixes().split(";");
				if (prefixes.length > 0) {
					txtPref1.setText(0 < prefixes.length ? prefixes[0] : "");
					txtPref2.setText(1 < prefixes.length ? prefixes[1] : "");
					txtPref3.setText(2 < prefixes.length ? prefixes[2] : "");
					txtPref4.setText(3 < prefixes.length ? prefixes[3] : "");
				}
			} else {
				txtPref1.setText("");
				txtPref2.setText("");
				txtPref3.setText("");
				txtPref4.setText("");
			}

			btnNext.setText("Save");

			return true;
		}

		return false;
	}

	protected void selectCountry(int position) {
		Log.i("EditProviderDialog", "selecting country at position " + position);
		if (_zone == null) {
			Log.i("EditProviderDialog",
					"cannot select a country...no zone defined");
			return;
		}
		if (countries == null) {
			Log.i("EditProviderDialog",
					"the countries for the zone " + _zone.getName()
							+ " have not been loaded yet...");
			return;
		}

		_country = countries.get(position);
		Log.i("EditProviderDialog", _country.getName() != null ? "country "
				+ _country.getName() + " selected" : "country at position "
				+ position + " is null");
	}

	protected void selectZone(int position) {
		_zone = zones.get(position);
		Log.i("DIALOG_NEW_Provider", "Zone " + zones.get(position).getName()
				+ " selected");
		country_list.setZone(_zone);
	}

	public void resetDialog() {
		Log.i("EditProviderDialog", "reseting the dialog...");
		_provider = null;
		id = -1;
		txtName.setText("");
		txtPref1.setText("");
		txtPref2.setText("");
		txtPref3.setText("");
		txtPref4.setText("");
		if (viewIndex == 1) {
			flipper.showPrevious();
			viewIndex = 0;
		}
	}

	@Override
	public void show() {
		Log.i("EditProviderDialog", "showing the dialog...");
		super.show();
		Log.i("EditProviderDialog", "dialog on screen...");
		bindZones();
		bindProvider();
	}

	@Override
	protected void onStart() {
		Log.i("EditProviderDialog", "Starting the dialog...");
		super.onStart();
		Log.i("EditProviderDialog", "dialog started...");
	}

	private void bindZones() {
		Log.i("EditProviderDialog", "binding zones...");
		if (zones == null) {
			zones_list.setAdapter(null);
			zones = zones_list.getZones();
		} else {
			Log.i("EditProviderDialog", "zones already bound...");
		}
	}

	@Override
	protected void onStop() {
		Log.i("EditProviderDialog", "Stopping the dialog...");
		super.onStop();
		Log.i("EditProviderDialog", "dialog stopped...");
	}

	public Provider getProvider() {
		return _provider;
	}
}
